package rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import Common.GoggleDB;
import SQL.plan.Plan;
import SQL.planner.Planner;
import SQL.query.Commit;
import SQL.query.SQL;
import SQL.query.StartTX;
import Transaction.Transaction;



@SuppressWarnings("serial") 
public class RemoteStatementImpl extends UnicastRemoteObject implements RemoteStatement {
	private RemoteConnectionImpl rconn;
	private RemoteResultSet rrs ; 

	public RemoteStatementImpl(RemoteConnectionImpl rconn) throws RemoteException {
		this.rconn = rconn;
	}

	public RemoteResultSet executeQuery(String qry) throws RemoteException {
		try {
			if ( rrs != null ) rrs.close() ; 
			rrs = null ; 
		}catch ( Exception e) { }
		try {
			Transaction tx = rconn.getTransaction();
			SQL sql=Planner.getSQL(qry);
			Plan pln = Planner.createQueryPlan(sql ,  rconn.getDbName() , tx );
			return ( rrs = new RemoteResultSetImpl(pln, rconn, sql ) ) ;
		}
		catch(Exception e) {
			if ( rconn.getAutoCommit() ) rconn.rollback();
			throw new RemoteException ( "error occur while executing: "+ qry );
		}
	}

	public int executeUpdate(String qry) throws RemoteException {
		try {
			if (Planner.getSQL(qry) instanceof StartTX)
			{
				rconn.setAutoCommit(false);
				return 0;
			}
			else if (Planner.getSQL(qry) instanceof Commit)
			{
				rconn.commit();
				rconn.setAutoCommit(true);
				return 0;
			}
			else
			{
				Transaction tx = rconn.getTransaction();
				int result = GoggleDB.planner.executeUpdate(Planner.getSQL(qry), rconn.getDbName() , tx);
				if ( rconn.getAutoCommit() ) rconn.commit();
				return result;
			}
		}
		catch( Exception e ) {
			//e.printStackTrace() ; 
			//if ( rconn.getAutoCommit() ) 
			rconn.rollback();
			throw new RemoteException ( "error occur while executing: "  + qry.toString() ); 
		}
	}
	
	protected void finalize() throws Throwable {
		rrs.close() ; 
		super.finalize(); 
	}
}
